import OSS from 'ali-oss'
import { getSTS, interfaceUploadFile } from '@/api/common.js'

export function Download(objKey, filename) {
  console.log(filename)
  const client = new OSS({
    /* 请替换成自己的 */
    region: 'oss-cn-hangzhou',
    accessKeyId: 'Svy57spMWowhVUhV',
    accessKeySecret: 'vmamZuzhEl2f7KYJoByVViMcbU9wBS',
    bucket: 'wskxoss'
  })
  return new Promise((resolve) => {
    const Name = filename
    const response = {
      'content-disposition': `attachment; filename=${encodeURIComponent(Name)}`
    }

    const url = client.signatureUrl(objKey, { response })
    resolve(url)
  }).catch((Error) => {
    console.log(Error)
  })
}

function onprogress(res, callback) {
  callback(Math.floor(res * 100))
}

export function uploadFile(file, callback) {
  return new Promise((resolve, reject) => {
    // getSTS().then((response) => {
    const time = new Date()
    const savePath =
      'd1000/tmp/uploads/' +
      time.getFullYear() +
      '/' +
      (time.getMonth() + 1) +
      '/' +
      time.getDate() +
      '/' +
      file.file.name
    const client = new OSS({
      region: 'oss-cn-hangzhou-zwynet-d01-a',
      // accessKeyId: response.data.accessKeyId,
      // accessKeySecret: response.data.accessKeySecret,
      // stsToken: response.data.securityToken,
      accessKeyId: 'Svy57spMWowhVUhV',
      accessKeySecret: 'vmamZuzhEl2f7KYJoByVViMcbU9wBS',
      // stsToken: response.data.securityToken,
      bucket: 'wskxoss',
      endpoint: 'oss-cn-hangzhou-zwynet-d01-a.internet.cloud.zj.gov.cn' // OSS 外网节点或自定义外部域名
    })
    client
      .multipartUpload(savePath, file.file, {
        progress: (res) => {
          callback && onprogress(res, callback)
        }
      })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
    // })
  })
}

//接口上传文件
export function uploadInterface(file, callback, reject) {
  let formData = new FormData()
  formData.append('file', file)
  interfaceUploadFile(formData)
    .then((res) => {
      callback && callback(res)
    })
    .catch(() => {
      reject && reject()
    })
}
